package com.woniu.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.dao.UserMapper;
import com.woniu.dao.WorkerMapper;
import com.woniu.entity.User;
import com.woniu.entity.UserExample;
import com.woniu.entity.Worker;
import com.woniu.entity.WorkerExample;
import com.woniu.util.JwtTokenUitl;
import com.woniu.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 用户登录成功
 */
@Component
public class MyAuthenticationSucess implements AuthenticationSuccessHandler {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private WorkerMapper workerMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ObjectMapper obj = new ObjectMapper();
        try {
            String account = request.getParameter("account");
            String tokenStr = JwtTokenUitl.createSign(account);

            //将用户的权限并且存入缓存
            Worker worker = workerMapper.getWorkerByAccount(account);
            String keys = worker.getAccount() + worker.getPassword();

            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            List<String> proces = new ArrayList<>();
            for (GrantedAuthority authority : authorities) {
                proces.add(authority.getAuthority());
            }

            String values = ops.get(keys);
            if (StringUtils.isEmpty(values)) {
                ops.set(keys, new ObjectMapper().writeValueAsString(proces));
            }
            ResponseResult<String> result = new ResponseResult(tokenStr, "登录成功", 200);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(result));
            writer.flush();
            writer.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
